class Solution1 {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        int[][] f = new int[n][k + 1];
        int[][] g = new int[n][k + 1];
        for (int j = 0; j <= k; j++) {
            f[0][j] = -prices[0];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= k; j++) {
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j - 1 >= 0) {
                    g[i][j] = Math.max(f[i - 1][j - 1] + prices[i], g[i][j]);
                }
            }
        }
        int ret = 0;
        for (int i = 0; i <= k; i++) {
            ret = Math.max(ret, g[n - 1][i]);
        }
        return ret;
    }
}